package com.example.myapplication;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.myapplication.pojo.IotDataObj;
import com.example.myapplication.pojo.Res;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.QMUIViewPager;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class IotHistoryActivity extends AppCompatActivity implements View.OnClickListener {
    private QMUITopBar mTopBar;
    private QMUIViewPager viewPager;
    private ArrayList<IotDataObj> datas;
    private ArrayList<PopupMenu> menus;
    private QMUIGroupListView groupListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_historical_data);

        ActionBar actionBar = getSupportActionBar();
        /*if (actionBar != null) {
            actionBar.hide();
        }*/
        mTopBar=findViewById(R.id.h_dtopbar);
        QMUIStatusBarHelper.translucent(this);// 沉浸式状态栏
        initTopBar();//初始化状态栏

        groupListView = findViewById(R.id.hd_groupListView);
        menus=new ArrayList<PopupMenu>();
        initdata();
    }

    private void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.blue));
        mTopBar.setTitleGravity(Gravity.LEFT);
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        /*mTopBar.setTitle("历史数据");*/
    }
    private void initdata(){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("http://192.168.43.209:8883/iot/getalldata")
                .method("GET", null)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.i("liaoyunfang",e.getMessage());
                Log.i("liaoyunfang","error");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.i("liaoyunfang","success");
                String res = response.body().string();
                Res r = JSON.parseObject(res, Res.class);
                JSONArray jsonArray = (JSONArray) r.getData();
                datas=new ArrayList<>(jsonArray.toJavaList(IotDataObj.class));
                Log.i("liaoyunfang","datas");
                Log.i("liaoyunfang",datas.toString());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //渲染ui
                        // 创建一个Section，并设置标题
                        QMUIGroupListView.Section section = QMUIGroupListView.newSection(IotHistoryActivity.this);
                        for (int i = 0; i < datas.size(); i++) {
                            QMUICommonListItemView itemView = groupListView.createItemView(datas.get(i).getTimestamp());
                            itemView.setTag(i);
                            PopupMenu popupMenu = new PopupMenu(IotHistoryActivity.this, itemView);

                            // 添加菜单项
                            IotDataObj iotDataObj = datas.get((Integer) itemView.getTag());
                            Log.i("liaoyunfang","test:   "+iotDataObj.toString());
                            popupMenu.getMenu().add(Menu.NONE, 1, Menu.NONE, "温度:"+iotDataObj.getTemperature()+"°C");
                            popupMenu.getMenu().add(Menu.NONE, 2, Menu.NONE, "湿度:"+iotDataObj.getHumidity()+"%");
                            popupMenu.getMenu().add(Menu.NONE, 2, Menu.NONE, "浊度:"+iotDataObj.getZhuoDu()+"FTU");
                            popupMenu.getMenu().add(Menu.NONE, 2, Menu.NONE, "前方障碍物距离:"+iotDataObj.getDistance()+"cm");
                            popupMenu.getMenu().add(Menu.NONE, 2, Menu.NONE, "GPS经纬度:"+"(" + iotDataObj.getGPSN() + " , " + iotDataObj.getGPSE() + ")");
                            popupMenu.getMenu().add(Menu.NONE, 6, Menu.NONE, "时间:"+iotDataObj.getTimestamp());
                            // 设置菜单项点击事件
                            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    // 处理菜单项点击事件
                                    switch (item.getItemId()) {
                                        case 1:
                                            // 菜单项1的处理逻辑
                                            break;
                                        case 2:
                                            // 菜单项2的处理逻辑
                                            break;
                                        case 3:
                                            // 菜单项3的处理逻辑
                                            break;
                                        case 4:
                                            // 菜单项3的处理逻辑
                                            break;
                                        case 5:
                                            // 菜单项3的处理逻辑
                                            break;
                                        case 6:
                                            // 菜单项3的处理逻辑
                                            break;
                                    }
                                    return true;
                                }
                            });
                            menus.add(popupMenu);
                            section.addItemView(itemView, IotHistoryActivity.this);
                        }
                        // 将Section添加到GroupListView中
                        section.addTo(groupListView);
                    }
                });
            }
        });
    }
    @Override
    public void onClick(View view) {
        Log.i("liaoyunfang", view.getTag().toString());
        menus.get((Integer) view.getTag()).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public  boolean onOptionsItemSelected(MenuItem item){

        int itemId = item.getItemId();
        Intent intent = new Intent();
        Log.i("liaoyunfang", String.valueOf(itemId));
        Log.i("liaoyunfang", String.valueOf(R.id.current_environment));
        if(itemId==R.id.current_environment){
            intent.setClass(IotHistoryActivity.this, IotActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }
}